<template>
	<div class="mod-config">
		<el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
<!--			<el-form-item>-->
<!--				<el-input v-model="dataForm.key" placeholder="参数名" clearable></el-input>-->
<!--			</el-form-item>-->
			<el-form-item>
<!--				<el-button @click="getDataList()">查询</el-button>-->
				<el-button type="primary" @click="addOrUpdateHandle()">新增计划</el-button>
				<el-button type="danger" @click="deleteHandle()"
					:disabled="dataListSelections.length <= 0">批量删除计划</el-button>
			</el-form-item>
		</el-form>

		<el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle"
			style="width: 100%;">
			<el-table-column type="selection" header-align="center" align="center">
			</el-table-column>
			<el-table-column prop="id" header-align="center" align="center" label="id" width="60">
			</el-table-column>
      <el-table-column type="expand" label="课程列表">
        <template slot-scope="scope">
          <el-table :data="scope.row.courses">
            <el-table-column prop="id" label="课程ID" header-align="center" align="center">
            </el-table-column>
            <el-table-column prop="name" label="课程名称"></el-table-column>
          </el-table>
        </template>
      </el-table-column>
			<el-table-column prop="name" header-align="center" align="center" label="计划名称">
			</el-table-column>
			<el-table-column prop="desc" header-align="center" align="center" label="计划简介" width="200" >
        <template slot-scope="scope">
          <el-popover
              placement="bottom"
              width="200"
              trigger="hover"
              :content="scope.row.desc">
<!--            <el-button slot="reference">hover 激活</el-button>-->
            <el-link :underline="false" slot="reference">
              {{
                scope.row.desc.length > 22 ? scope.row.desc.slice(0, 22) + '.......' : scope.row.desc
              }}
            </el-link>
          </el-popover>
        </template>
			</el-table-column>
			<el-table-column prop="goal" header-align="center" align="center" label="计划目标">
			</el-table-column>
<!--			<el-table-column prop="courses" header-align="center" align="center" label="课程名称" width="200">-->
<!--        -->
<!--			</el-table-column>-->

			<el-table-column prop="createTime" header-align="center" align="center" label="创建时间" width="170">
        <template slot-scope="scope">
          {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
			</el-table-column>
			<el-table-column prop="days" header-align="center" align="center" label="训练周期">
			</el-table-column>
			<el-table-column prop="trainLength" header-align="center" align="center" label="每日训练时长">
			</el-table-column>
			<el-table-column prop="calorie" header-align="center" align="center" label="卡路里">
			</el-table-column>
			<el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
				<template slot-scope="scope">
					<el-button type="text" size="small" @click="addOrUpdateHandle(scope.row)">修改</el-button>
					<el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination align="right"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
			  :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageSize"
        :total="totalPage"
			  layout="total, sizes, prev, pager, next, jumper">
		</el-pagination>
		<!-- 弹窗, 新增 / 修改 -->
		<add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
	</div>
</template>


<script>
	import AddOrUpdate from './plan-add-or-update'
  import dayjs from "dayjs";
	export default {
    computed: {
      dayjs() {
        return dayjs
      }
    },
		data() {
			return {
				dataForm: {
					key: ''
				},
				dataList: [],
				pageIndex: 1,
				pageSize: 10,
				totalPage: 0,
				dataListLoading: false,
				dataListSelections: [],
				addOrUpdateVisible: false
			}
		},
		components: {
			AddOrUpdate
		},
		mounted() {
			this.getDataList()
		},
		methods: {

			// 获取数据列表
        getDataList() {
				this.dataListLoading = true

        this.$http.post('/plan/searchPlanList', {
          'pageNum': this.pageIndex,
          'pageSize': this.pageSize
        }).then( ({
                                           data
        }) => {
          // console.log(data);
          if (data && data.code === 200) {
            this.dataList = data.page.list
            this.totalPage = data.page.total

            this.dataList = data.page.list.map(item => {
              return { ...item, courses: [] }; // 为每个元素添加一个空的 courses 字段
            });

            // 假设你有一个名为 dataList 的数组，包含了每个元素的 courseId 字段
            this.dataList.forEach(async item => {
              const courseIdList = JSON.parse(item.courseId); // 将字符串解析为数组


              const courses = [];
              // 遍历 courseIdList，为每个 courseId 查询课程名称
              await Promise.all(courseIdList.map(async courseId => {
                try {

                  const response = await this.$http.get(`/course/id/${courseId}`)
                  const courseData = response.data.data;
                  // 创建一个对象来存储id和课程名称
                  const course = {}

                  course.id = courseId;
                  course.name = courseData.name.toString();
                  courses.push(course)


                } catch (error) {
                  // 处理请求错误
                  console.error(`课程id为：${courseId}的课程数据获取失败，该课程可能已被删除`, error);
                }
              }));

              // 将获取到的课程名称数组添加到元素的 courseNames 字段
              // item.courseNames = JSON.stringify(courseNames);
              // const index = this.dataList.indexOf(item)
              // this.dataList[index].courseNames = courseNames.join(",")
              // console.log(JSON.stringify(this.dataList));
              item.courses = courses;
              // 在这里输出
              // console.log(item.courseNames);
            });
            setTimeout(()=>{
              // console.log(JSON.stringify(this.dataList));

            },2000)




          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false;
        })
			},
			// 每页数
			sizeChangeHandle(val) {
				this.pageSize = val
				this.pageIndex = 1
				this.getDataList()
			},
			// 当前页
			currentChangeHandle(val) {
				this.pageIndex = val
				this.getDataList()
			},
			// 多选
			selectionChangeHandle(val) {
				this.dataListSelections = val
			},
			// 新增 / 修改
			addOrUpdateHandle(row) {
				this.addOrUpdateVisible = true
				this.$nextTick(() => {
					this.$refs.addOrUpdate.init(row)
				})
			},
			// 删除
			deleteHandle(id) {
				var ids = id ? [id] : this.dataListSelections.map(item => {
					return item.id
				})
        // console.log(ids);
        // ${ids.join(',')}
				this.$confirm(`确定删除id=${ids}的计划吗?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						url: this.$http.defaults.baseURL + '/plan/deletePlanByIds',
						method: 'post',
						data: { ids : ids}
					}).then(({
						data
					}) => {
						if (data && data.code === 200) {
							this.$message({
								message: '操作成功',
								type: 'success',
								duration: 1500,
								onClose: () => {
									this.getDataList()
								}
							})
						} else {
							this.$message.error(data.msg)
						}
					})
				}).catch(error => {

        })
			},


		}
	}


</script>